import { Component, OnInit, Input, SimpleChanges } from '@angular/core';
import {
  NzFormatEmitEvent,
  NzModalService
} from 'ng-zorro-antd';
import { EventEmitter, Output } from '@angular/core';
import { Utils } from 'src/app/common/helper/util-helper';
@Component({
  selector: 'app-tree-edit',
  templateUrl: './tree-edit.component.html',
  styleUrls: ['./tree-edit.component.scss']
})
export class TreeEditComponent implements OnInit {
  @Input('nodesList') nodesList: any;
  @Input('ModalTitle') ModalTitle: string;
  @Output() handleCreateOrModify = new EventEmitter();
  @Output() handleDelete = new EventEmitter();
  constructor(private modalService: NzModalService) { }

  ngOnInit() {
  }
  // tslint:disable-next-line: member-ordering
  public editNodeKey: any = null;
  public isAddEditModalVisible: boolean = false
  public addEditValue: string
  public activedNode: any
  public nodeStauts: number // 1为添加 2为编辑 3为删除
  public nzExpandAll = true

  ngOnChanges(changes: SimpleChanges): void {
    if (changes['nodesList']) {
      this.nodesList = changes['nodesList'].currentValue;
    }
  }
  /**
   * 提交数据
   */
  public submit() {
    this.handleCreateOrModify.emit()
  }
  /**
   * 编辑表单
   * @param node 
   */
  public edit(node) {
    this.resetForm()
    this.addEditValue = node.title
    console.info(node)
    console.info(this.activedNode)
    this.nodeStauts = 2
    this.editNodeKey = node.origin.id;
    this.isAddEditModalVisible = true;
    let EditInput = document.getElementById('EditInput');
    setTimeout(() => {
      EditInput.focus();
    }, 0);
  }
  /**
   * 
   * 重置表单
   */
  public resetForm() {
    this.addEditValue = '';
  }

  /**
    * 回车事件
    * @param e <Event>
    */
  public keyupEvent(e) {
    console.log(e.keyCode)
    if (e.keyCode === 13) {
      Utils.enter(e, this.submit.bind(this));
      return;
    }
    if (e.keyCode === 27) {
      this.isAddEditModalVisible = false;
      return;
    }

  }

  /**
   * 点击条目
   * @param event
   */
  public nzClick(event: NzFormatEmitEvent) {
    if (!this.activedNode) {
      this.activedNode = event.node;
    } else if (this.activedNode === event.node) {
      // this.activedNode = null;
    } else {
      this.activedNode = event.node;
    }
    console.log(this.activedNode)

  }
  /**
   * 删除模态框
   * @param node 
   */
  public showDeleteConfirm(node): void {
    this.modalService.error({
      nzTitle: '删除',
      nzContent: `<b>确认要删除 ${node.title} 吗</b>`,
      nzOkText: '确认',
      nzOkType: 'danger',
      nzOnOk: () => {
        this.nodeStauts = 3
        const deleteArry = []
        deleteArry.push(node.key)
        this.handleDelete.emit(deleteArry)
      },
      nzCancelText: '取消',
      nzOnCancel: () => console.log('Cancel')
    });
  }
  nzEvent(event: NzFormatEmitEvent): void {
    console.log(event);
  }
  /**
   * 后端数据转换为tree组件数据
   * @param data 原数组
   * @param attributes 配置属性
   */
  public transformTreeNode(data, attributes) {
    let resData = data;
    let tree = [];

    for (let i = 0; i < resData.length; i++) {
      if (resData[i].parentId === attributes.rootId) {
        let obj = {
          id: resData[i][attributes.id],
          title: resData[i][attributes.name],
          name: resData[i][attributes.name],
          children: [],
          parentId: attributes.rootId,
          key: resData[i][attributes.id],
          type: resData[i]['type'],
          projectId: resData[i]['projectId'],
          // expanded: true
          isLeaf: true
        };
        tree.push(obj);
        resData.splice(i, 1);
        i--;
      }
    }
    run(tree);
    function run(chiArr) {
      if (resData.length !== 0) {
        for (let i = 0; i < chiArr.length; i++) {
          for (let j = 0; j < resData.length; j++) {
            if (chiArr[i].id === resData[j][attributes.parentId]) {
              let obj = {
                id: resData[j][attributes.id],
                title: resData[j][attributes.name],
                name: resData[j][attributes.name],
                children: [],
                parentId: resData[j][attributes.parentId],
                key: resData[j][attributes.id],
                type: resData[j]['type'],
                projectId: resData[j]['projectId'],
                // expanded: true
                isLeaf: true
              };
              chiArr[i].children.push(obj);
              chiArr[i].isLeaf = false;
              resData.splice(j, 1);
              j--;
            }
          }
          run(chiArr[i].children);
        }
      }
    }
    return tree;
  }
}
